package com.demo.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 通过condition监视器来精确的通知执行的顺序
 * Condition 精准的通知和唤醒线程
 */
public class C {
    public static void main(String[] args) {
        Ticket3 ticket = new Ticket3();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ticket.printA();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ticket.printB();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ticket.printC();
            }
        },"C").start();

    }
}

//生产消费问题
//判断等待，业务，通知
class Ticket3{
    private int num = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA(){
        lock.lock();
        try {
            //等待 ——> 操作 ——> 通知
            if(num != 1){
                condition1.await();
            }
            num = 2;
            System.out.println(Thread.currentThread().getName()+"=>AAAAA");
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();
        try {
            //等待 ——> 操作 ——> 通知
            if(num != 2){
                condition2.await();
            }
            num = 3;
            System.out.println(Thread.currentThread().getName()+"=>BBBBB");
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try {
            //等待 ——> 操作 ——> 通知
            if(num != 3){
                condition3.await();
            }
            num = 1;
            System.out.println(Thread.currentThread().getName()+"=>CCCCC");
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}